#ifndef AUTOCONFIGHELP_H
#define AUTOCONFIGHELP_H

#include "configmanager.h"
#include <QObject>
#include <QString>
#include <QMetaObject>
#include <QMetaMethod>

template<typename T, typename U>
class AutoPropertyHelper {
public:
    AutoPropertyHelper(T* instance, const QString& key, const QString& configSection)
        : instance_(instance), key_(key), configSection_(configSection) {
        // 初始化配置值
        value_ = ConfigManager::getInstance().getParameter<U>(configSection, key);

        // 绑定配置变化信号
        // QObject::connect(&ConfigManager::getInstance(), &ConfigManager::configDataChanged, instance_,
        //                  [this](const QString& section, const QString& changedKey) {
        //                      if (configSection_ == section && key_ == changedKey) {
        //                          value_ = ConfigManager::getInstance().getParameter<U>(configSection_, key_);
        //                          QMetaObject::invokeMethod(instance_,
        //                                                    (key_ + "Changed").toLatin1().data(),
        //                                                    Qt::QueuedConnection);
        //                      }
        //                  });

        QObject::connect(&ConfigManager::getInstance(), &ConfigManager::valueTableLoad, instance_,
                         [this]() {

                             value_ = ConfigManager::getInstance().getParameter<U>(configSection_, key_);
                             qDebug() <<"valueTableLoad AUTO " << configSection_ << "[" <<key_ << "] :" << value_;
                             QMetaObject::invokeMethod(instance_,
                                                       (key_ + "Changed").toLatin1().data(),
                                                       Qt::QueuedConnection);
                         });


    }

    // 隐式转换
    operator U() const {
        return value_;
    }

    // 赋值运算符
    AutoPropertyHelper& operator=(const U& newValue) {
        if (value_ != newValue) {
            value_ = newValue;
            qDebug() <<"setValue " << configSection_ << "[" <<key_ << "] :" << value_;
            ConfigManager::getInstance().setParameter(configSection_, key_, value_);
            QMetaObject::invokeMethod(instance_, (key_ + "Changed").toLatin1().data(),
                                      Qt::QueuedConnection);
        }
        return *this;
    }

private:
    T* instance_;
    QString key_;
    U value_;
    const QString configSection_;
};


#define AUTO_CONFIG_PROPERTY(className, configSection, type, name) \
private: \
    AutoPropertyHelper<className, type> m_##name{this, #name, configSection}; \
    Q_SIGNALS: \
    void name##Changed(); \
    public: \
    Q_PROPERTY(type name READ get_##name WRITE set_##name NOTIFY name##Changed) \
    type get_##name() const { return m_##name; } \
    void set_##name(const type &value) { m_##name = value; }


#endif // AUTOCONFIGHELP_H
